package weeny.pre.control;

import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import prefuse.Display;
import prefuse.controls.DragControl;
import prefuse.visual.VisualItem;

/**
 * An extention of DragControl, which maintains a list of listeners to perform
 * some customized actions before or after the item movements, such as pressed
 * released, or dragged.
 * 
 * @author weeny
 */
public class MoreDragControl extends DragControl{
	public static class DragListener{
		//functions called before the item-related actions
		public void beforeItemPressed(VisualItem item, MouseEvent e){}
		public void beforeItemRelease(VisualItem item, MouseEvent e){}
		public void beforeItemDragged(VisualItem item, MouseEvent e){}
		//functions called after the item-related actions
		public void afterItemPressed(VisualItem item, MouseEvent e){}
		public void afterItemRelease(VisualItem item, MouseEvent e){}
		public void afterItemDragged(VisualItem item, MouseEvent e){}
	}
	protected List<DragListener> listenerList = new ArrayList<DragListener>();
	public void addDragListener(DragListener listener){
		if (listenerList.contains(listener)) {
			return;
		}
		else {
			listenerList.add(listener);
		}
		repaint = false;
	}
	public boolean removeDragListener(DragListener listener){
		boolean flag = listenerList.remove(listener);
		//this action is coming from DragControl. If it is not null it
		if (listenerList.isEmpty() && action == null) {
			repaint = true;
		}
		return flag;
	}
	@Override
	public void itemPressed(VisualItem item, MouseEvent e) {
		for (DragListener listener : listenerList) {
			listener.beforeItemPressed(item, e);
		}
		super.itemPressed(item, e);
		for (DragListener listener : listenerList) {
			listener.afterItemPressed(item, e);
		}
	}
	@Override
	public void itemReleased(VisualItem item, MouseEvent e) {
		for (DragListener listener : listenerList) {
			listener.beforeItemRelease(item, e);
		}
		super.itemReleased(item, e);
		for (DragListener listener : listenerList) {
			listener.afterItemRelease(item, e);
		}
	}
	@Override
	public void itemDragged(VisualItem item, MouseEvent e) {
		for (DragListener listener : listenerList) {
			listener.beforeItemDragged(item, e);
		}
		super.itemDragged(item, e);
		for (DragListener listener : listenerList) {
			listener.afterItemDragged(item, e);
		}
		if (!listenerList.isEmpty()) {
			((Display)e.getComponent()).getVisualization().repaint();
		}
	}
}